// pages/ca/ca.js
const app = getApp()
var that = ''

Page({
    data: {
        accessToken: "",
        isShow: false,
        image: '/images/banner.png',
        base64Img: '',
        token: '',
        result: []
    },
    onShow() {
        // 获取accessToken
        var time = wx.getStorageSync("time")
        var curTime = new Date().getTime()
        var timeInt = parseInt(time)
        var timeNum = parseInt((curTime - timeInt) / (1000 * 60 * 60 * 24))
        console.log("=======" + timeNum)
        var accessToken = wx.getStorageSync("access_token")
        console.log("====accessToken===" + accessToken + "a")
        // accessToken超过30天过期
        if (timeNum > 28 || (accessToken == "" ||
                accessToken == null || accessToken == undefined)) {
            this.accessTokenFunc()
        } else {
            this.setData({
                accessToken: wx.getStorageSync("access_token")
            })
        }
    },
    //选择图片按钮
    imgSelect() {
        this.setData({
            isShow: false
        })
        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success: (res) => {
                const tempFilePaths = res.tempFilePaths[0]
                this.getB64ByUrl(tempFilePaths)
                this.setData({
                    image: tempFilePaths
                })
            }
        })
    },

    //图片转为base64
    getB64ByUrl(url) {
        wx.getFileSystemManager().readFile({
            filePath: url,
            encoding: 'base64',
            success: (res) => {
                this.setData({
                    base64Img: res.data
                })
            }
        })
    },
    // 获取百度的AccessToken
    accessTokenFunc() {
        wx.request({
            url: 'https://aip.baidubce.com/oauth/2.0/token',
            data: {
                grant_type: 'client_credentials',
                client_id: 'xVBluR4U7blzrWh1KFTsE1th', //应用的API Key
                client_secret: 'RGCZ3qDdEpkYhrdI8PGlqjKdG8pPnGV7' //应用的Secret Key
            },
            header: {
                'Content-Type': 'application/json' // 默认值
            },
            success: res => {
                this.setData({
                    accessToken: res.data.access_token //获取到token
                })
                console.log('获取到的token', this.data.accessToken)
                wx.setStorageSync("access_token", this.data.accessToken)
                wx.setStorageSync("time", new Date().getTime())
            },
            fail: res => {
                wx.clearStorageSync("access_token")
                wx.showToast({
                    icon: 'error',
                    title: '调用失败,请重新尝试',
                })
            }
        })
    },

    //植物识别
    plant() {
        if (!this.data.base64Img) {
            this.setData({
                isShow: true
            })
            return
        }
        this.getResult()
    },
    //获取识别结果
    getResult() {
        let that = this
        wx.request({
            // url: 'https://aip.baidubce.com/rest/2.0/image-classify/v1/plant?access_token=' + token,
            url: 'https://aip.baidubce.com/rest/2.0/image-classify/v1/plant',
            method: 'POST',
            data: {
                access_token: that.data.accessToken,
                image: this.data.base64Img
            },
            header: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            success: (res) => {
                console.log(res);
                this.setData({
                    result: that.resultFilter(res.data.result)
                })
            },
            complete: () => {
                wx.hideLoading()
            }
        })
    },
    //result结果过滤
    resultFilter(arr) {
        arr.forEach((item) => {
            item.score = (item.score.toFixed(4) * 100).toFixed(2) + '%'
        })
        return arr
    },
})
